package com.situ.layuimini.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.situ.layuimini.entity.User;
import com.situ.layuimini.exception.NoLoginException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TokenUtil {

    private static String secret;

    //生成token的方法
    public static String token(User user) {
        return JWT.create()
                .withClaim("id", user.getId())
                .withClaim("username", user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 8))
                .sign(Algorithm.HMAC256(secret));
    }

    //解析token方法
    public static User parse(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            Claim claim = decodedJWT.getClaim("id");
            User u = new User();
            u.setId(claim.asInt());
            Claim claim2 = decodedJWT.getClaim("username");
            u.setUsername(claim2.asString());
            return u;
        } catch (TokenExpiredException e) {
            System.out.println("token已过期");
            throw new NoLoginException();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Value("${token.secret}")
    public void setSecret(String secret) {
        TokenUtil.secret = secret;
    }
}
